package cn.big.bigd.ybp.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.big.bigd.ybp.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.big.bigd.ybp.model.YbpRole;
import cn.big.bigd.ybp.model.YbpUser;
import cn.big.bigd.ybp.service.YbpUserService;

/**
 * @author fan
 */

@Controller
public class MainController implements ErrorController {

    @Autowired
    YbpUserService userService;

    private static final String ERROR_PATH = "/error";



    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @RequestMapping(ERROR_PATH)
    public String error(HttpServletRequest request, Model model) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> map = errorAttributes.getErrorAttributes(requestAttributes, true);
        model.addAttribute("errors", map.values());
        return "error";
    }

    @RequestMapping("/login")
    public String login() {
        return "ybp/userlogin";
    }

    @RequestMapping(value = {"", "/home", "/index"})
    public String index() {
        return "redirect:http://bigd.big.ac.cn/conference/ybp";
        // return "ybp/index";
    }

    @RequestMapping(value = "/weixin", method = RequestMethod.POST)
    public void mes(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map<String, String> map = MessageUtil.xmlToMap(request);
        PrintWriter out = response.getWriter();
        String toUserName = map.get("ToUserName");
        String fromUserName = map.get("FromUserName");
        String msgType = map.get("MsgType");
        String content = map.get("Content");
        String message = null;
        if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {
            if ("1".equals(content)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenu());
            } else if ("2".equals(content)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.secondMenu());
            } else if ("?".equals(content) || "？".equals(content)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
            } else {
                TextMessage text = new TextMessage();
                text.setFromUserName(toUserName);
                text.setToUserName(fromUserName);
                text.setCreateTime(new Date().getTime());
                text.setMsgType("text");
                text.setContent("梁少华说:" + content);
                message = MessageUtil.textMessageToXml(text);

            }


        } else if (MessageUtil.MESSAGE_EVENT.equals(msgType)) {
            String eventType = map.get("Event");
            if (MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
            }

        }
        System.out.print(message);
        out.print(message);


    }

    @RequestMapping("/weixin")
    public void weixin(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = response.getWriter();
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);

        }

    }

    /**
     * 处理用户注册请求
     *
     * @param email
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(String email, Integer resend, HttpServletRequest request, Model model) {

        return "redirect:http://bigd.big.ac.cn/conference/ybp";
        /*String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        // 随机生成6位密码
        String password = PasswordUtils.genRandomNum(6);
        int status = 0;// 未激活
        YbpUser u = userService.findByEmail(email);
        if(resend==1){
            userService.deleteById(u.getId());
            u =null;
        }
        if (u != null) {
            if (u.getStatus() == 0) {

                    model.addAttribute("resend", 1);
                    model.addAttribute("email", email);
                    model.addAttribute("error", "该邮箱" + email + "已注册，请去邮箱激活......");
                    return "ybp/error";
            } else {
                model.addAttribute("error", "该邮箱" + email + "已注册，请直接登录......");
                return "ybp/error";
            }
        } else {

            // 先插入未激活状态数据
            YbpUser user = new YbpUser();
            user.setEmail(email);
            user.setPassword(userService.encode(password));
            user.setStatus(status);
            user.addRole(YbpRole.USER);
            Calendar c = Calendar.getInstance();
            // 现在的时间(单位：毫秒)
            long time = c.getTimeInMillis();
            Date regtime = new Date(time);
            user.setRegtime(regtime);
            String token = userService.encode(email + password + time);
            user.setToken(token);
            long tokenExptime = (long) (time + 1000 * 60 * 60 * 24);
            user.setTokenExptime(Long.toString(tokenExptime));
            try {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                StringBuffer sb = new StringBuffer("<div style=\"padding:24px 20px;\">您好，" + email + "<br/>" + "您的密码为: "
                        + password + "<br/><br/>" + "生物信息学在我国蓬勃发展，越来越多的青年学者逐渐崭露头角。为更好地促进青年学者的学术发展，加强青年学者的交流与互动，"
                        + "分享最新的学术进展和科研动态，商讨生物信息领域所面临的困难与挑战，"
                        + "哈佛大学刘小乐教授和国内一批青年学者倡导在国内举办青年生物信息PI研讨会，并于2012年成功举办了第一届会议!<br/><br/>" +
                        "研讨会秉承“吴瑞精神”，关注青年学者的发展；采取轮值制，每年由国内不同学术单位承办；研讨会不设组委、不支付课酬、食宿费用，一切从简；拟邀请报告人由往届参会学者提名确定；研讨会在邀请报告结束之后，一般会就一个或若干重要的问题进行激烈的讨论，不求达成共识，但求能够分享观点及看法。<br/>"
                        + "<br/>请点击下面链接激活账号，24小时生效，否则重新注册账号，链接只能使用一次，请尽快激活并填写信息！<br/><br/>");
                if (!email.contains("big.ac.cn")) {


                    sb.append("<a href=\"" + host + "/activateCheck?email=");
                    sb.append(email);
                    sb.append("&token=");
                    sb.append(token);
                    sb.append("\" target=\"_blank\"\">");
                }
                sb.append(host + "/activateCheck?email=");
                sb.append(email);
                sb.append("&token=");
                sb.append(token);
                if (!email.contains("big.ac.cn")) {
                    sb.append("</a>");
                }
                sb.append("<br/>如果以上链接无法点击，请把上面网页地址复制到浏览器地址栏中打开,或选中链接，右键选择新窗口打开<br/><br/><br/>"
                        + "<p>交流&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;共享&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                        + "合作&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;发展</p><br/>" + sdf.format(new Date()) + "</div></div>");

                // 发送邮件
                EmailUtils.sendHtmlMail("第五届青年生物信息PI研讨会（2016年8月12-13日）- 账户激活", sb.toString(), email);
                userService.save(user);// 保存注册信息
                model.addAttribute("reg", email);
                return "ybp/success";
            } catch (Exception e) {

                model.addAttribute("error", "保存用户信息失败或邮件发送失败" + e.toString());
                return "ybp/error";

            }

        }*/

    }


    /**
     * 处理用户激活请求
     *
     * @param email
     * @param token
     * @param model
     * @return
     */
    @RequestMapping("/activateCheck")
    public String activateCheck(String email, String token, Model model) {

        Calendar c = Calendar.getInstance();
        System.out.println(token);
        // 现在的时间(单位：毫秒)
        long curtime = c.getTimeInMillis();
        YbpUser user = userService.findByStatusAndToken(0, token);
        if (user != null) {
            long token_exptime = Long.parseLong(user.getTokenExptime());
            // 如果激活码过期
            if (curtime > token_exptime) {
                // 如果过期就先删除相应用户信息，然后重新发送邮件
                System.out.println("如果过期就先删除相应用户信息，然后重新发送邮件");
                userService.deleteById(user.getId());
                model.addAttribute("error", "激活码已过期,请重新注册！");
                return "ybp/error";
            } else {
                // 更新用户激活状态
                userService.updateStatus(1, user.getId());
                model.addAttribute("user", user);
                model.addAttribute("message", "激活成功！请登录后提交会议注册信息");
                return "ybp/userlogin";
            }
        } else {
            model.addAttribute("error", "用户已经激活");
            return "ybp/error";
        }
    }


}
